//
//  ViewController.swift
//  backtime
//
//  Created by Pro on 2018/2/5.
//  Copyright © 2018年 Pro. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    fileprivate var i = 60 // 倒计时时间
    fileprivate var timer:Timer? // 倒计时定时器
    var getCodeBtn = UIButton()
    var label = UILabel()
    var tField = UITextField()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.groupTableViewBackground
        getCodeBtn.frame = CGRect(x: 10, y: 100, width: 150, height: 50)
        getCodeBtn.setTitle("2.点击开始按钮", for: .normal)
        getCodeBtn.addTarget(self, action: #selector(ViewController.startTimer), for: UIControlEvents.touchUpInside)
        getCodeBtn.backgroundColor = UIColor.gray
        view.addSubview(getCodeBtn)
        
        
        label.frame = CGRect(x: 10, y: 160, width: 100, height: 50)
        label.backgroundColor = UIColor.gray
        label.textAlignment =  NSTextAlignment(rawValue: 1)!
        view.addSubview(label)
        
        tField.frame = CGRect(x: 0, y: 220, width: 200, height: 50)
        tField.backgroundColor = UIColor.white
        tField.placeholder = "1.请输入初始化秒数"
        view.addSubview(tField)
        
        
        
    }

    
  
    // 开始计时
    @objc private func startTimer() {
        i = Int(tField.text!)! // 将初始化的秒数转化为整型
        getCodeBtn.isEnabled = false
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
    }
    
    // 停止计时
    @objc private func stopTimer() {
        getCodeBtn.isEnabled = true
        timer?.invalidate()
        timer = nil
        
    }
    
    // 倒计时秒数分割处理
    @objc private func countDown() {
        i -= 1;var leftMin = "00";var RightSec = "00";if i >= 60 {let minT = i / 60;if minT < 10 {leftMin = "0" + String(minT)}else if minT >= 10 && minT < 60{leftMin = String(minT)} else if minT >= 60{}else{leftMin = "00"}}
        let secT = i % 60;if secT >= 10 {RightSec = String(secT)} else if secT > 0 && secT < 10 {RightSec = "0" + String(secT)};if i < 0 {stopTimer()} else {
            label.text = leftMin + ":" + RightSec
        }
    }
    
    
    
}

